<?php


namespace App\Services;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

/**
 * 阿里云发送短信
 * Class AliSms
 * @package App\Services
 */
class AliSms
{
    protected static $access_key = 'LTAI4G2Bj9wMwZqCsHRLAUUh';

    protected static $access_secret = 'pBHL8MVy68ro7Jr9ZXZMclUsK2B2Tg';

    protected static $sginName = '同好慈孝';

    protected static $temp = [
        1   => 'SMS_207545176' //验证码 ${code}
    ];

    public static function sendCode($mobile, int $temp, array $data)
    {
        AlibabaCloud::accessKeyClient(self::$access_key,self::$access_secret)
                        ->regionId('cn-hangzhou')
                        ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                            ->host('dysmsapi.aliyuncs.com')
                            ->product('Dysmsapi')
                            // ->scheme('https') // https | http
                            ->version('2017-05-25')
                            ->action('SendSms')
                            ->method('POST')
                            ->options([
                                'query' => [
                                    'RegionId' => "cn-hangzhou",
                                    'PhoneNumbers' => $mobile,
                                    'SignName' => self::$sginName,
                                    'TemplateCode' => self::$temp[$temp],
                                    'TemplateParam' => json_encode($data),
                                ],
                            ])
                            ->request();
            return $result;
        }catch (ClientException $exception){

            return [
                'Code'      => $exception->getErrorCode(),
                'Message'   => $exception->getErrorMessage(),
            ];
        }catch (ServerException $exception){

            return [
                'Code'      => $exception->getErrorCode(),
                'Message'   => $exception->getErrorMessage(),
            ];
        }
    }

}
